<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>场景详情管理 - 御物联</title>
    <style>
        *{margin:0;padding:0;box-sizing:border-box}
        :root{--primary:#409EFF;--stage-bg:#EDE3D3;--bg:#F5F7FA;--text:#303133;--subtext:#909399;--card:#FFFFFF;--border:#EBEEF5;--ok:#67C23A;--warn:#E6A23C;--danger:#F56C6C}
        body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;background:var(--stage-bg);color:var(--text)}
        .page{min-height:100vh;max-width:480px;margin:0 auto;background:var(--bg);padding-bottom:calc(80px + env(safe-area-inset-bottom))}
        
        /* 页头样式与页脚保持一致 */
        .header-box{position:sticky;top:0;z-index:20;background:var(--card);border-bottom:1px solid var(--border);box-shadow:0 -2px 8px rgba(0,0,0,.04);padding:12px;display:flex;justify-content:space-between;align-items:center;margin:0;border-radius:0}
        .back-btn{display:flex;align-items:center;gap:8px;color:var(--text);text-decoration:none;font-size:14px;font-weight:500}
        .back-icon{font-size:18px;font-weight:bold}
        .user{margin-left:auto;padding:0 10px;height:32px;border-radius:16px;background:var(--card);border:1px solid var(--border);display:flex;align-items:center;gap:8px;color:var(--text);box-shadow:0 1px 3px rgba(0,0,0,.03)}
        .user-avatar{width:22px;height:22px;border-radius:50%;background:var(--primary);color:#fff;display:flex;align-items:center;justify-content:center;font-size:12px}
        
        /* 页面标题 */
        .page-title{font-size:18px;font-weight:600;color:var(--text);padding:16px 12px;background:var(--card);border-bottom:1px solid var(--border);margin:0 12px;border-radius:8px 8px 0 0;margin-top:12px}
        
        /* 场景信息卡片 */
        .scene-info-card{background:var(--card);margin:0 12px 12px;border-radius:0 0 8px 8px;padding:16px;box-shadow:0 2px 6px rgba(0,0,0,.03);border:1px solid var(--border);border-top:none}
        .scene-info-row{display:flex;align-items:center;margin-bottom:12px;padding:8px 0}
        .scene-info-row:last-child{margin-bottom:0}
        .scene-info-label{width:70px;font-size:13px;color:var(--subtext);font-weight:500;flex-shrink:0}
        .scene-info-value{flex:1;font-size:14px;color:var(--text)}
        .scene-info-input{flex:1;height:36px;border:1px solid var(--border);border-radius:6px;padding:0 12px;font-size:14px;color:var(--text);background:var(--card)}
        .scene-info-input:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 2px rgba(64,158,255,.2)}
        .scene-info-input:disabled{background:var(--bg);color:var(--subtext);cursor:not-allowed}
        .scene-info-textarea{flex:1;min-height:60px;border:1px solid var(--border);border-radius:6px;padding:8px 12px;font-size:14px;color:var(--text);background:var(--card);resize:vertical;font-family:inherit}
        .scene-info-textarea:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 2px rgba(64,158,255,.2)}
        
        /* 执行对象区域 */
        .execution-section{background:var(--card);margin:0 12px 12px;border-radius:8px;padding:16px;box-shadow:0 2px 6px rgba(0,0,0,.03);border:1px solid var(--border)}
        .section-title{font-size:15px;font-weight:600;color:var(--text);margin-bottom:12px;display:flex;align-items:center;justify-content:space-between}
        .add-object-btn{background:var(--primary);color:#fff;border:none;border-radius:6px;padding:6px 12px;font-size:13px;cursor:pointer;display:flex;align-items:center;gap:4px}
        .add-object-btn:hover{background:#66b1ff}
        
        /* 命令列表 */
        .command-list{margin-top:12px}
        .command-item{background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:12px;margin-bottom:8px;position:relative}
        .command-item:last-child{margin-bottom:0}
        .command-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
        .command-title{font-size:13px;font-weight:600;color:var(--text)}
        .command-actions{display:flex;gap:6px}
        .command-edit-btn{background:var(--primary);color:#fff;border:none;border-radius:4px;padding:3px 6px;font-size:11px;cursor:pointer}
        .command-delete-btn{background:var(--danger);color:#fff;border:none;border-radius:4px;padding:3px 6px;font-size:11px;cursor:pointer}
        .command-fields{display:grid;grid-template-columns:1fr 1fr;gap:8px}
        .command-field{display:flex;flex-direction:column;gap:3px}
        .command-field-label{font-size:11px;color:var(--subtext);font-weight:500}
        .command-field-input{height:28px;border:1px solid var(--border);border-radius:4px;padding:0 6px;font-size:11px;color:var(--text);background:var(--card)}
        .command-field-input:focus{outline:none;border-color:var(--primary)}
        .command-field-select{height:28px;border:1px solid var(--border);border-radius:4px;padding:0 6px;font-size:11px;color:var(--text);background:var(--card);cursor:pointer}
        
        /* 底部操作按钮 */
        .bottom-actions{position:fixed;left:0;right:0;bottom:0;height:60px;padding:8px 12px;padding-bottom:calc(8px + env(safe-area-inset-bottom));background:var(--card);border-top:1px solid var(--border);display:flex;gap:12px;justify-content:center;box-shadow:0 -2px 8px rgba(0,0,0,.04);max-width:480px;margin:0 auto}
        .btn{height:44px;border-radius:8px;border:1px solid var(--border);background:#fff;color:var(--text);font-size:15px;cursor:pointer;transition:all 0.3s ease;display:flex;align-items:center;justify-content:center;flex:1;max-width:120px}
        .btn-primary{background:var(--primary);color:#fff;border-color:var(--primary)}
        .btn-primary:hover{background:#66b1ff}
        .btn-primary:disabled{background:var(--border);color:var(--subtext);cursor:not-allowed}
        .btn-secondary{background:var(--bg);color:var(--text);border-color:var(--border)}
        .btn-secondary:hover{background:var(--border)}
        
        /* 空状态 */
        .empty-state{text-align:center;padding:30px 16px;color:var(--subtext)}
        .empty-icon{font-size:36px;margin-bottom:12px;opacity:0.5}
        .empty-text{font-size:13px;margin-bottom:8px}
        .empty-hint{font-size:11px;color:var(--subtext)}
        
        /* 抽屉样式 */
        .drawer-mask{position:fixed;inset:0;background:rgba(0,0,0,.35);opacity:0;pointer-events:none;transition:opacity .25s ease;z-index:999}
        .drawer-mask.open{opacity:1;pointer-events:auto}
        .drawer{position:fixed;top:0;right:0;height:100vh;width:86vw;max-width:420px;background:var(--card);border-left:1px solid var(--border);box-shadow:-12px 0 24px rgba(0,0,0,.12);transform:translateX(100%);transition:transform .25s ease;z-index:1000;display:flex;flex-direction:column}
        .drawer.open{transform:translateX(0)}
        .drawer-header{display:flex;align-items:center;justify-content:space-between;padding:12px 14px;border-bottom:1px solid var(--border);font-weight:600}
        .drawer-body{padding:0 14px 14px;color:var(--subtext);font-size:14px;overflow:auto}
        .drawer-row{display:flex;justify-content:space-between;padding:12px 0;border-bottom:1px solid var(--border);color:var(--text)}
        .drawer-row:last-child{border-bottom:none}
        .drawer-foot{display:flex;gap:10px;padding:12px;background:var(--bg);border-top:1px solid var(--border)}
        
        /* 设备选择弹框 */
        .device-modal{position:fixed;inset:0;background:rgba(0,0,0,.5);opacity:0;pointer-events:none;transition:opacity .25s ease;z-index:1000;display:flex;align-items:center;justify-content:center;padding:20px}
        .device-modal.open{opacity:1;pointer-events:auto}
        .device-dialog{background:var(--card);border-radius:12px;width:100%;max-width:400px;max-height:80vh;overflow:hidden;transform:scale(0.9);transition:transform .25s ease}
        .device-modal.open .device-dialog{transform:scale(1)}
        .device-header{padding:16px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
        .device-title{font-size:16px;font-weight:600;color:var(--text)}
        .device-close{width:24px;height:24px;border:none;background:none;font-size:20px;color:var(--subtext);cursor:pointer}
        .device-body{padding:20px;max-height:60vh;overflow-y:auto}
        .device-list{display:flex;flex-direction:column;gap:8px}
        .device-item{padding:12px;border:1px solid var(--border);border-radius:8px;cursor:pointer;transition:all 0.3s ease;background:var(--card)}
        .device-item:hover{background:var(--bg);border-color:var(--primary)}
        .device-item.selected{background:rgba(64,158,255,0.1);border-color:var(--primary)}
        .device-name{font-size:14px;font-weight:500;color:var(--text);margin-bottom:4px}
        .device-type{font-size:12px;color:var(--subtext)}
        
        /* 参数选择弹框 */
        .param-modal{position:fixed;inset:0;background:rgba(0,0,0,.5);opacity:0;pointer-events:none;transition:opacity .25s ease;z-index:1001;display:flex;align-items:center;justify-content:center;padding:20px}
        .param-modal.open{opacity:1;pointer-events:auto}
        .param-dialog{background:var(--card);border-radius:12px;width:100%;max-width:400px;max-height:80vh;overflow:hidden;transform:scale(0.9);transition:transform .25s ease}
        .param-modal.open .param-dialog{transform:scale(1)}
        .param-header{padding:16px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
        .param-title{font-size:16px;font-weight:600;color:var(--text)}
        .param-close{width:24px;height:24px;border:none;background:none;font-size:20px;color:var(--subtext);cursor:pointer}
        .param-body{padding:20px;max-height:60vh;overflow-y:auto}
        .param-type-tabs{display:flex;gap:8px;margin-bottom:16px}
        .param-type-tab{padding:8px 16px;border:1px solid var(--border);border-radius:6px;background:var(--card);color:var(--text);cursor:pointer;transition:all 0.3s ease;font-size:14px}
        .param-type-tab.active{background:var(--primary);color:#fff;border-color:var(--primary)}
        .param-list{display:flex;flex-direction:column;gap:8px}
        .param-item{padding:12px;border:1px solid var(--border);border-radius:8px;cursor:pointer;transition:all 0.3s ease;background:var(--card)}
        .param-item:hover{background:var(--bg);border-color:var(--primary)}
        .param-item.selected{background:rgba(64,158,255,0.1);border-color:var(--primary)}
        .param-name{font-size:14px;font-weight:500;color:var(--text);margin-bottom:4px}
        .param-desc{font-size:12px;color:var(--subtext)}
        
        /* 控制面板弹框 */
        .control-modal{position:fixed;inset:0;background:rgba(0,0,0,.5);opacity:0;pointer-events:none;transition:opacity .25s ease;z-index:1002;display:flex;align-items:center;justify-content:center;padding:20px}
        .control-modal.open{opacity:1;pointer-events:auto}
        .control-dialog{background:var(--card);border-radius:12px;width:100%;max-width:400px;max-height:80vh;overflow:hidden;transform:scale(0.9);transition:transform .25s ease}
        .control-modal.open .control-dialog{transform:scale(1)}
        .control-header{padding:16px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
        .control-title{font-size:16px;font-weight:600;color:var(--text)}
        .control-close{width:24px;height:24px;border:none;background:none;font-size:20px;color:var(--subtext);cursor:pointer}
        .control-body{padding:20px;max-height:60vh;overflow-y:auto}
        .control-actions{padding:16px 20px;border-top:1px solid var(--border);display:flex;gap:12px;justify-content:flex-end}
        .control-btn{height:36px;padding:0 16px;border-radius:6px;border:1px solid var(--border);background:var(--card);color:var(--text);font-size:14px;cursor:pointer;transition:all 0.3s ease}
        .control-btn.primary{background:var(--primary);color:#fff;border-color:var(--primary)}
        .control-btn.primary:hover{background:#66b1ff}
    </style>
</head>
<body>
    <div class="page">
        <!-- 页头 -->
        <div class="header-box">
            <a href="scene-manage.html" class="back-btn">
                <span class="back-icon">←</span>
                <span>返回场景列表</span>
            </a>
            <button class="user" id="userBtn" type="button" title="查看个人信息">
                <span class="user-avatar" id="userAvatar">U</span>
                <span id="userName">用户</span>
            </button>
        </div>

        <!-- 页面标题 -->
        <div class="page-title" id="pageTitle">场景详情管理</div>

        <!-- 场景信息卡片 -->
        <div class="scene-info-card">
            <div class="scene-info-row">
                <div class="scene-info-label">场景名称</div>
                <input type="text" class="scene-info-input" id="sceneNameInput" placeholder="请输入场景名称">
            </div>
            <div class="scene-info-row">
                <div class="scene-info-label">场景描述</div>
                <textarea class="scene-info-textarea" id="sceneDescInput" placeholder="请输入场景作用描述"></textarea>
            </div>
            <div class="scene-info-row">
                <div class="scene-info-label">所属项目</div>
                <input type="text" class="scene-info-input" id="projectInput" disabled>
            </div>
            <div class="scene-info-row">
                <div class="scene-info-label">最后执行</div>
                <input type="text" class="scene-info-input" id="lastExecInput" disabled>
            </div>
        </div>

        <!-- 执行对象区域 -->
        <div class="execution-section">
            <div class="section-title">
                <span>执行命令列表</span>
                <button class="add-object-btn" id="addCommandBtn">
                    <span>+</span>
                    <span>新增执行对象</span>
                </button>
            </div>
            
            <!-- 命令列表 -->
            <div class="command-list" id="commandList">
                <div class="empty-state" id="emptyState">
                    <div class="empty-icon">📋</div>
                    <div class="empty-text">暂无执行命令</div>
                    <div class="empty-hint">点击"新增执行对象"添加命令</div>
                </div>
            </div>
        </div>

        <!-- 底部操作按钮 -->
        <div class="bottom-actions">
            <button class="btn btn-secondary" id="cancelBtn">取消</button>
            <button class="btn btn-primary" id="saveBtn" disabled>保存</button>
        </div>
    </div>

    <!-- 个人信息抽屉 -->
    <div class="drawer-mask" id="drawerMask"></div>
    <aside class="drawer" id="userDrawer" aria-label="个人信息">
        <div class="drawer-header"><span>个人信息</span></div>
        <div class="drawer-body">
            <div class="drawer-row" style="padding:20px 0 12px; text-align:center;">
                <button id="userInfoBtn" class="btn btn-primary" style="width:100%; height:48px; font-size:16px;">查看个人信息</button>
            </div>
            <div class="drawer-row" style="border-bottom:none; padding:12px 0 20px; text-align:center;">
                <button id="controlPanelBtn" class="btn" style="width:100%; height:48px; font-size:16px; background:var(--ok); color:#fff; border-color:var(--ok);">操作面板展示</button>
            </div>
        </div>
        <div class="drawer-foot">
            <button id="changePasswordBtn" class="btn" style="flex:1; background:var(--primary); color:#fff; border:none;">修改密码</button>
            <button id="logoutBtn" class="btn btn-danger">退出登录</button>
            <button id="closePanel" class="btn">关闭</button>
        </div>
    </aside>

    <!-- 设备选择弹框 -->
    <div class="device-modal" id="deviceModal">
        <div class="device-dialog">
            <div class="device-header">
                <div class="device-title">选择设备</div>
                <button class="device-close" id="deviceClose">&times;</button>
            </div>
            <div class="device-body">
                <div class="device-list" id="deviceList">
                    <!-- 设备列表将通过JavaScript动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 参数选择弹框 -->
    <div class="param-modal" id="paramModal">
        <div class="param-dialog">
            <div class="param-header">
                <div class="param-title">选择参数类型</div>
                <button class="param-close" id="paramClose">&times;</button>
            </div>
            <div class="param-body">
                <div class="param-type-tabs">
                    <div class="param-type-tab active" data-type="data">数据</div>
                    <div class="param-type-tab" data-type="control">控制</div>
                </div>
                <div class="param-list" id="paramList">
                    <!-- 参数列表将通过JavaScript动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 控制面板弹框 -->
    <div class="control-modal" id="controlModal">
        <div class="control-dialog">
            <div class="control-header">
                <div class="control-title" id="controlTitle">控制设置</div>
                <button class="control-close" id="controlClose">&times;</button>
            </div>
            <div class="control-body" id="controlBody">
                <!-- 控制面板内容将通过JavaScript动态生成 -->
            </div>
            <div class="control-actions">
                <button class="control-btn" id="controlCancel">取消</button>
                <button class="control-btn primary" id="controlConfirm">确认</button>
            </div>
        </div>
    </div>

    <script>
        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 用户显示初始化
            const u = JSON.parse(localStorage.getItem('currentUser')||'{}');
            document.getElementById('userName').textContent = u.name || '用户';
            document.getElementById('userAvatar').textContent = (u.name||'U').slice(0,1);
            
            // 获取URL参数
            const urlParams = new URLSearchParams(window.location.search);
            const mode = urlParams.get('mode'); // 'edit' 或 'add'
            const sceneName = urlParams.get('sceneName');
            const project = urlParams.get('project') || '物联网内部测试系统';
            
            // 初始化页面
            initPage(mode, sceneName, project);
            
            // 绑定事件
            bindEvents();
        });
        
        // 初始化页面
        function initPage(mode, sceneName, project) {
            const pageTitle = document.getElementById('pageTitle');
            const sceneNameInput = document.getElementById('sceneNameInput');
            const sceneDescInput = document.getElementById('sceneDescInput');
            const projectInput = document.getElementById('projectInput');
            const lastExecInput = document.getElementById('lastExecInput');
            
            if (mode === 'edit') {
                pageTitle.textContent = '编辑场景';
                sceneNameInput.value = sceneName || '';
                // 根据场景名称设置对应的描述
                sceneDescInput.value = getSceneDescription(sceneName);
                projectInput.value = project;
                lastExecInput.value = '2024-01-15 18:30';
            } else if (mode === 'add') {
                pageTitle.textContent = '新增场景';
                sceneNameInput.value = '';
                sceneDescInput.value = '';
                projectInput.value = project;
                lastExecInput.value = '未执行';
            }
        }
        
        // 获取场景描述
        function getSceneDescription(sceneName) {
            const descriptions = {
                '回家模式': '自动开启照明、调节空调温度、播放欢迎音乐，营造温馨的回家氛围',
                '离家模式': '关闭所有照明设备、调节空调至节能模式、启动安防系统，确保家庭安全',
                '睡眠模式': '调暗照明、降低空调温度、关闭娱乐设备，营造舒适的睡眠环境',
                '节能模式': '优化设备运行参数、降低能耗、延长设备寿命，实现绿色环保的智能控制',
                '办公模式': '调节照明亮度、设置适宜温度、关闭娱乐设备，营造专注的办公环境',
                '娱乐模式': '开启氛围照明、调节音响设备、优化观影环境，提供沉浸式娱乐体验',
                '安防模式': '启动监控系统、开启报警设备、关闭非必要照明，确保家庭安全防护',
                '清洁模式': '开启空气净化、调节湿度、优化通风系统，保持室内环境清洁健康'
            };
            return descriptions[sceneName] || '';
        }
        
        // 绑定事件
        function bindEvents() {
            // 抽屉交互
            const drawer = document.getElementById('userDrawer');
            const mask = document.getElementById('drawerMask');
            
            function openDrawer() {
                drawer.classList.add('open');
                mask.classList.add('open');
            }
            
            function closeDrawer() {
                drawer.classList.remove('open');
                mask.classList.remove('open');
            }
            
            document.getElementById('userBtn').addEventListener('click', openDrawer);
            document.getElementById('closePanel').addEventListener('click', closeDrawer);
            mask.addEventListener('click', closeDrawer);
            document.getElementById('userInfoBtn').addEventListener('click', () => {
                closeDrawer();
                location.href = 'user-info.html';
            });
            document.getElementById('controlPanelBtn').addEventListener('click', () => {
                closeDrawer();
                location.href = 'control-panel-demo.html';
            });
            document.getElementById('logoutBtn').addEventListener('click', () => {
                localStorage.removeItem('currentUser');
                location.href = 'mobile-login-demo.html';
            });
            
            // 新增命令按钮
            document.getElementById('addCommandBtn').addEventListener('click', addCommand);
            
            // 保存和取消按钮
            document.getElementById('saveBtn').addEventListener('click', saveScene);
            document.getElementById('cancelBtn').addEventListener('click', cancelEdit);
            
            // 场景名称和描述输入监听
            document.getElementById('sceneNameInput').addEventListener('input', updateSaveButton);
            document.getElementById('sceneDescInput').addEventListener('input', updateSaveButton);
            
            // 弹框关闭事件
            document.getElementById('deviceClose').addEventListener('click', () => {
                document.getElementById('deviceModal').classList.remove('open');
            });
            
            document.getElementById('paramClose').addEventListener('click', () => {
                document.getElementById('paramModal').classList.remove('open');
            });
            
            document.getElementById('controlClose').addEventListener('click', () => {
                document.getElementById('controlModal').classList.remove('open');
            });
            
            document.getElementById('controlCancel').addEventListener('click', () => {
                document.getElementById('controlModal').classList.remove('open');
            });
            
            document.getElementById('controlConfirm').addEventListener('click', () => {
                document.getElementById('controlModal').classList.remove('open');
                saveCommand();
                // 显示保存提醒
                showSaveAlert();
            });
            
            // 参数类型切换
            document.querySelectorAll('.param-type-tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    document.querySelectorAll('.param-type-tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    selectedParamType = this.getAttribute('data-type');
                    
                    // 重新生成参数列表
                    const paramList = document.getElementById('paramList');
                    paramList.innerHTML = '';
                    const params = selectedParamType === 'data' ? dataParams : controlParams;
                    
                    params.forEach(param => {
                        const paramItem = document.createElement('div');
                        paramItem.className = 'param-item';
                        paramItem.innerHTML = `
                            <div class="param-name">${param.name}</div>
                            <div class="param-desc">${param.desc}</div>
                        `;
                        paramItem.addEventListener('click', () => selectParam(param));
                        paramList.appendChild(paramItem);
                    });
                });
            });
            
            // 控制面板交互
            document.addEventListener('input', function(e) {
                if (e.target.id === 'tempRange') {
                    document.getElementById('tempValue').textContent = e.target.value + '°C';
                } else if (e.target.id === 'brightnessRange') {
                    document.getElementById('brightnessValue').textContent = e.target.value + '%';
                } else if (e.target.id === 'openingRange') {
                    document.getElementById('openingValue').textContent = e.target.value + '%';
                }
            });
        }
        
        // 全局变量
        let selectedDevice = null;
        let selectedParamType = 'data';
        let selectedParam = null;
        let currentCommandIndex = -1; // -1表示新增，其他表示编辑索引
        
        // 设备数据
        const deviceData = [
            { id: 'device001', name: '温度传感器01', type: '传感器设备' },
            { id: 'device002', name: '湿度传感器02', type: '传感器设备' },
            { id: 'device003', name: '智能开关03', type: '控制设备' },
            { id: 'device004', name: '空调控制器04', type: '控制设备' },
            { id: 'device005', name: '亮度控制器05', type: '控制设备' },
            { id: 'device006', name: '开度控制器06', type: '控制设备' }
        ];
        
        // 数据参数
        const dataParams = [
            { id: 'temp', name: '温度', desc: '实时温度数据' },
            { id: 'humidity', name: '湿度', desc: '实时湿度数据' },
            { id: 'pressure', name: '压力', desc: '实时压力数据' },
            { id: 'switch_status', name: '开关状态', desc: '开关当前状态' },
            { id: 'floor', name: '楼层', desc: '设备所在楼层' }
        ];
        
        // 控制参数
        const controlParams = [
            { id: 'switch', name: '开关名称', desc: '开关类控制器', type: 'switch' },
            { id: 'aircon', name: '红外遥控器控制面板', desc: '红外遥控器控制面板（不能获取实时控制数据）', type: 'aircon' },
            { id: 'opening', name: '开度控制器', desc: '开度类控制器', type: 'opening' },
            { id: 'brightness', name: '亮度控制器', desc: '亮度类控制器', type: 'brightness' }
        ];
        
        // 添加命令
        function addCommand() {
            currentCommandIndex = -1;
            selectedDevice = null;
            selectedParam = null;
            showDeviceModal();
        }
        
        // 编辑命令
        function editCommand(btn) {
            const commandItem = btn.closest('.command-item');
            const commandIndex = Array.from(commandItem.parentNode.children).indexOf(commandItem);
            currentCommandIndex = commandIndex;
            
            // 获取当前命令数据
            const deviceName = commandItem.querySelector('.command-field-input[placeholder="请输入设备名称"]').value;
            const sensorName = commandItem.querySelector('.command-field-input[placeholder="请输入传感器名称"]').value;
            const sensorType = commandItem.querySelector('.command-field-input[value="数据"], .command-field-input[value="控制"]').value;
            const command = commandItem.querySelector('.command-field-input[placeholder="请输入执行命令"]').value;
            
            // 根据命令类型判断是数据还是控制
            if (command.includes('采集')) {
                selectedParamType = 'data';
                selectedParam = dataParams.find(p => p.name === sensorName) || dataParams[0];
            } else {
                selectedParamType = 'control';
                selectedParam = controlParams.find(p => p.name === sensorName) || controlParams[0];
                
                // 如果是开关控制，解析开关状态
                if (selectedParam.type === 'switch' && command.includes('打开')) {
                    window.currentSwitchState = 'on';
                } else if (selectedParam.type === 'switch' && command.includes('关闭')) {
                    window.currentSwitchState = 'off';
                }
                // 如果是空调控制，解析空调状态
                else if (selectedParam.type === 'aircon') {
                    if (command.includes('关闭空调')) {
                        window.currentAirconPower = 'off';
                    } else if (command.includes('打开空调')) {
                        window.currentAirconPower = 'on';
                        // 解析温度
                        const tempMatch = command.match(/温度(\d+)°C/);
                        window.currentAirconTemp = tempMatch ? parseInt(tempMatch[1]) : 25;
                        // 解析模式
                        if (command.includes('制冷')) {
                            window.currentAirconMode = 'cool';
                        } else if (command.includes('制热')) {
                            window.currentAirconMode = 'heat';
                        } else {
                            window.currentAirconMode = 'cool';
                        }
                    }
                }
            }
            
            // 找到对应的设备
            selectedDevice = deviceData.find(d => d.name === deviceName) || deviceData[0];
            
            showDeviceModal();
        }
        
        // 显示设备选择弹框
        function showDeviceModal() {
            const modal = document.getElementById('deviceModal');
            const deviceList = document.getElementById('deviceList');
            
            // 生成设备列表
            deviceList.innerHTML = '';
            deviceData.forEach(device => {
                const deviceItem = document.createElement('div');
                deviceItem.className = 'device-item';
                deviceItem.innerHTML = `
                    <div class="device-name">${device.name}</div>
                    <div class="device-type">${device.type}</div>
                `;
                deviceItem.addEventListener('click', () => selectDevice(device));
                deviceList.appendChild(deviceItem);
            });
            
            modal.classList.add('open');
        }
        
        // 选择设备
        function selectDevice(device) {
            selectedDevice = device;
            document.getElementById('deviceModal').classList.remove('open');
            showParamModal();
        }
        
        // 显示参数选择弹框
        function showParamModal() {
            const modal = document.getElementById('paramModal');
            const paramList = document.getElementById('paramList');
            
            // 生成参数列表
            paramList.innerHTML = '';
            const params = selectedParamType === 'data' ? dataParams : controlParams;
            
            params.forEach(param => {
                const paramItem = document.createElement('div');
                paramItem.className = 'param-item';
                paramItem.innerHTML = `
                    <div class="param-name">${param.name}</div>
                    <div class="param-desc">${param.desc}</div>
                `;
                paramItem.addEventListener('click', () => selectParam(param));
                paramList.appendChild(paramItem);
            });
            
            modal.classList.add('open');
        }
        
        // 选择参数
        function selectParam(param) {
            selectedParam = param;
            document.getElementById('paramModal').classList.remove('open');
            
            if (selectedParamType === 'data') {
                // 数据参数直接保存
                saveCommand();
            } else {
                // 控制参数需要打开控制面板
                showControlModal();
            }
        }
        
        // 显示控制面板弹框
        function showControlModal() {
            const modal = document.getElementById('controlModal');
            const title = document.getElementById('controlTitle');
            const body = document.getElementById('controlBody');
            
            // 如果是空调类型，显示为"红外遥控器控制面板"
            if (selectedParam.type === 'aircon') {
                title.textContent = '红外遥控器控制面板';
            } else {
                title.textContent = `${selectedParam.name} - 控制设置`;
            }
            
            // 根据控制类型生成不同的控制面板
            let controlHTML = '';
            switch(selectedParam.type) {
                case 'switch':
                    controlHTML = generateSwitchControl();
                    break;
                case 'aircon':
                    controlHTML = generateAirconControl();
                    break;
                case 'brightness':
                    controlHTML = generateBrightnessControl();
                    break;
                case 'opening':
                    controlHTML = generateOpeningControl();
                    break;
            }
            
            body.innerHTML = controlHTML;
            modal.classList.add('open');
            
            // 如果是开关控制，恢复之前选择的状态
            if (selectedParam.type === 'switch' && window.currentSwitchState) {
                setTimeout(() => {
                    selectSwitchState(window.currentSwitchState);
                }, 100);
            }
            // 如果是空调控制，恢复之前选择的状态
            else if (selectedParam.type === 'aircon' && window.currentAirconPower) {
                setTimeout(() => {
                    selectAirconPower(window.currentAirconPower);
                }, 100);
            }
        }
        
        // 生成开关控制面板
        function generateSwitchControl() {
            return `
                <div style="text-align: center; padding: 20px;">
                    <div style="margin-bottom: 20px;">
                        <button class="control-btn" id="switchOnBtn" onclick="selectSwitchState('on')" style="margin-right: 10px;">打开</button>
                        <button class="control-btn" id="switchOffBtn" onclick="selectSwitchState('off')">关闭</button>
                    </div>
                    <div id="switchStatus" style="font-size: 14px; color: var(--subtext);">请选择开关状态</div>
                </div>
            `;
        }
        
        // 选择开关状态
        function selectSwitchState(state) {
            const onBtn = document.getElementById('switchOnBtn');
            const offBtn = document.getElementById('switchOffBtn');
            const status = document.getElementById('switchStatus');
            
            // 更新按钮状态
            if (state === 'on') {
                onBtn.classList.add('primary');
                offBtn.classList.remove('primary');
                status.textContent = '已选择：打开';
                status.style.color = 'var(--primary)';
            } else {
                offBtn.classList.add('primary');
                onBtn.classList.remove('primary');
                status.textContent = '已选择：关闭';
                status.style.color = 'var(--primary)';
            }
            
            // 保存选择的状态
            window.currentSwitchState = state;
        }
        
        // 生成空调控制面板
        function generateAirconControl() {
            return `
                <div style="text-align:center; color:var(--subtext); font-size:12px; margin-bottom:16px; padding:10px; background:rgba(255,193,7,.1); border-radius:8px;">
                    ⚠️ 注意：不能获取实时控制数据
                </div>
                <div class="aircon-controls" style="margin: 20px 0;">
                    <div class="aircon-power" style="display: flex; gap: 16px; justify-content: center; margin-bottom: 20px;">
                        <button class="control-btn" id="airconOnBtn" onclick="selectAirconPower('on')" style="flex: 1; height: 50px; font-size: 16px; font-weight: 600; background: var(--ok); color: #fff; border: none; border-radius: 8px;">打开空调</button>
                        <button class="control-btn" id="airconOffBtn" onclick="selectAirconPower('off')" style="flex: 1; height: 50px; font-size: 16px; font-weight: 600; background: var(--danger); color: #fff; border: none; border-radius: 8px;">关闭空调</button>
                    </div>
                    <div class="aircon-temp" id="airconTempControls" style="text-align: center; display: none;">
                        <div class="temp-label" style="font-size: 14px; color: var(--subtext); margin-bottom: 12px;">温度调节</div>
                        <div class="temp-controls" style="display: flex; align-items: center; gap: 16px; justify-content: center;">
                            <button class="control-btn temp-btn" onclick="changeAirconTemp(-1)" style="width: 40px; height: 40px; border-radius: 50%; font-size: 20px; font-weight: bold;">-</button>
                            <div class="temp-display" id="airconTempDisplay" style="font-size: 24px; font-weight: 600; color: var(--primary); min-width: 60px;">25°C</div>
                            <button class="control-btn temp-btn" onclick="changeAirconTemp(1)" style="width: 40px; height: 40px; border-radius: 50%; font-size: 20px; font-weight: bold;">+</button>
                        </div>
                        <div class="temp-mode" style="margin-top: 16px;">
                            <div class="mode-buttons" style="display: flex; gap: 8px; justify-content: center;">
                                <button class="control-btn mode-btn" onclick="setAirconMode('cool')" id="airconCoolBtn" style="padding: 8px 16px; border-radius: 20px; font-size: 14px;">制冷</button>
                                <button class="control-btn mode-btn" onclick="setAirconMode('heat')" id="airconHeatBtn" style="padding: 8px 16px; border-radius: 20px; font-size: 14px;">制热</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        // 选择空调电源状态
        function selectAirconPower(power) {
            const onBtn = document.getElementById('airconOnBtn');
            const offBtn = document.getElementById('airconOffBtn');
            const tempControls = document.getElementById('airconTempControls');
            
            // 更新按钮状态
            if (power === 'on') {
                onBtn.style.opacity = '1';
                offBtn.style.opacity = '0.6';
                tempControls.style.display = 'block';
                // 设置默认温度控制状态
                window.currentAirconTemp = 25;
                window.currentAirconMode = 'cool';
                updateAirconDisplay();
            } else {
                onBtn.style.opacity = '0.6';
                offBtn.style.opacity = '1';
                tempControls.style.display = 'none';
            }
            
            // 保存选择的状态
            window.currentAirconPower = power;
        }
        
        // 改变空调温度
        function changeAirconTemp(delta) {
            if (window.currentAirconPower !== 'on') return;
            
            window.currentAirconTemp = Math.max(16, Math.min(30, (window.currentAirconTemp || 25) + delta));
            updateAirconDisplay();
        }
        
        // 设置空调模式
        function setAirconMode(mode) {
            if (window.currentAirconPower !== 'on') return;
            
            window.currentAirconMode = mode;
            updateAirconDisplay();
        }
        
        // 更新空调显示
        function updateAirconDisplay() {
            const tempDisplay = document.getElementById('airconTempDisplay');
            const coolBtn = document.getElementById('airconCoolBtn');
            const heatBtn = document.getElementById('airconHeatBtn');
            
            if (tempDisplay) {
                tempDisplay.textContent = (window.currentAirconTemp || 25) + '°C';
            }
            
            if (coolBtn && heatBtn) {
                coolBtn.style.background = (window.currentAirconMode === 'cool') ? 'var(--primary)' : 'var(--card)';
                coolBtn.style.color = (window.currentAirconMode === 'cool') ? '#fff' : 'var(--text)';
                heatBtn.style.background = (window.currentAirconMode === 'heat') ? 'var(--primary)' : 'var(--card)';
                heatBtn.style.color = (window.currentAirconMode === 'heat') ? '#fff' : 'var(--text)';
            }
        }
        
        // 生成亮度控制面板
        function generateBrightnessControl() {
            return `
                <div style="text-align: center; padding: 20px;">
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; margin-bottom: 8px; font-size: 14px;">亮度调节</label>
                        <input type="range" id="brightnessRange" min="0" max="100" value="50" style="width: 100%; margin-bottom: 8px;">
                        <div id="brightnessValue" style="font-size: 14px; color: var(--primary);">50%</div>
                    </div>
                </div>
            `;
        }
        
        // 生成开度控制面板
        function generateOpeningControl() {
            return `
                <div style="text-align: center; padding: 20px;">
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; margin-bottom: 8px; font-size: 14px;">开度调节</label>
                        <input type="range" id="openingRange" min="0" max="100" value="0" style="width: 100%; margin-bottom: 8px;">
                        <div id="openingValue" style="font-size: 14px; color: var(--primary);">0%</div>
                    </div>
                </div>
            `;
        }
        
        // 设置控制值
        function setControlValue(value) {
            // 这里可以添加控制值的设置逻辑
            console.log('设置控制值:', value);
        }
        
        // 显示保存提醒
        function showSaveAlert() {
            const alertDiv = document.createElement('div');
            alertDiv.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: var(--card);
                border: 1px solid var(--border);
                border-radius: 8px;
                padding: 20px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                z-index: 2000;
                text-align: center;
                min-width: 200px;
            `;
            alertDiv.innerHTML = `
                <div style="font-size: 16px; color: var(--text); margin-bottom: 12px;">✅</div>
                <div style="font-size: 14px; color: var(--text);">命令已保存</div>
            `;
            
            document.body.appendChild(alertDiv);
            
            // 2秒后自动移除
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.parentNode.removeChild(alertDiv);
                }
            }, 2000);
        }
        
        // 保存命令
        function saveCommand() {
            const commandList = document.getElementById('commandList');
            const emptyState = document.getElementById('emptyState');
            
            // 隐藏空状态
            if (emptyState) {
                emptyState.style.display = 'none';
            }
            
            // 生成命令信息
            let commandInfo = '';
            if (selectedParamType === 'data') {
                commandInfo = `采集${selectedParam.name}数据`;
            } else {
                // 根据控制类型生成具体的命令信息
                if (selectedParam.type === 'switch') {
                    const switchState = window.currentSwitchState || 'off';
                    commandInfo = `控制${selectedParam.name} - ${switchState === 'on' ? '打开' : '关闭'}`;
                } else if (selectedParam.type === 'aircon') {
                    const power = window.currentAirconPower || 'off';
                    if (power === 'off') {
                        commandInfo = `红外遥控器控制面板 - 关闭空调（不能获取实时控制数据）`;
                    } else {
                        const temp = window.currentAirconTemp || 25;
                        const mode = window.currentAirconMode || 'cool';
                        const modeText = mode === 'cool' ? '制冷' : '制热';
                        commandInfo = `红外遥控器控制面板 - 打开空调 温度${temp}°C ${modeText}（不能获取实时控制数据）`;
                    }
                } else if (selectedParam.type === 'brightness') {
                    const brightness = document.getElementById('brightnessRange')?.value || '50';
                    commandInfo = `控制${selectedParam.name} - 亮度${brightness}%`;
                } else if (selectedParam.type === 'opening') {
                    const opening = document.getElementById('openingRange')?.value || '0';
                    commandInfo = `控制${selectedParam.name} - 开度${opening}%`;
                } else {
                    commandInfo = `控制${selectedParam.name}`;
                }
            }
            
            // 创建或更新命令项
            let commandItem;
            if (currentCommandIndex === -1) {
                // 新增命令
                commandItem = document.createElement('div');
                commandItem.className = 'command-item';
                commandList.appendChild(commandItem);
            } else {
                // 编辑命令
                commandItem = commandList.children[currentCommandIndex];
            }
            
            commandItem.innerHTML = `
                <div class="command-header">
                    <div class="command-title">执行命令 ${currentCommandIndex === -1 ? commandList.children.length : currentCommandIndex + 1}</div>
                    <div class="command-actions">
                        <button class="command-edit-btn" onclick="editCommand(this)">编辑</button>
                        <button class="command-delete-btn" onclick="deleteCommand(this)">删除</button>
                    </div>
                </div>
                <div class="command-fields">
                    <div class="command-field">
                        <div class="command-field-label">设备名称</div>
                        <input type="text" class="command-field-input" placeholder="请输入设备名称" value="${selectedDevice.name}" readonly>
                    </div>
                    <div class="command-field">
                        <div class="command-field-label">传感器名称</div>
                        <input type="text" class="command-field-input" placeholder="请输入传感器名称" value="${selectedParam.name}" readonly>
                    </div>
                    <div class="command-field">
                        <div class="command-field-label">传感器类型</div>
                        <input type="text" class="command-field-input" value="${selectedParamType === 'data' ? '数据' : '控制'}" readonly>
                    </div>
                    <div class="command-field">
                        <div class="command-field-label">执行命令</div>
                        <input type="text" class="command-field-input" placeholder="请输入执行命令" value="${commandInfo}" readonly>
                    </div>
                </div>
            `;
            
            updateSaveButton();
        }
        
        // 删除命令
        function deleteCommand(btn) {
            if (confirm('确定要删除这个执行命令吗？')) {
                const commandItem = btn.closest('.command-item');
                commandItem.remove();
                
                // 检查是否还有命令
                const commandList = document.getElementById('commandList');
                if (commandList.children.length === 0) {
                    const emptyState = document.getElementById('emptyState');
                    if (emptyState) {
                        emptyState.style.display = 'block';
                    }
                }
                
                updateSaveButton();
            }
        }
        
        // 更新保存按钮状态
        function updateSaveButton() {
            const sceneName = document.getElementById('sceneNameInput').value.trim();
            const sceneDesc = document.getElementById('sceneDescInput').value.trim();
            const commandList = document.getElementById('commandList');
            const hasCommands = commandList.children.length > 0;
            const saveBtn = document.getElementById('saveBtn');
            
            saveBtn.disabled = !sceneName || !sceneDesc || !hasCommands;
        }
        
        // 保存场景
        function saveScene() {
            const sceneName = document.getElementById('sceneNameInput').value.trim();
            const sceneDesc = document.getElementById('sceneDescInput').value.trim();
            const commandList = document.getElementById('commandList');
            
            if (!sceneName) {
                alert('请输入场景名称');
                return;
            }
            
            if (!sceneDesc) {
                alert('请输入场景描述');
                return;
            }
            
            if (commandList.children.length === 0) {
                alert('请至少添加一个执行命令');
                return;
            }
            
            // 收集命令数据
            const commands = [];
            commandList.querySelectorAll('.command-item').forEach((item, index) => {
                const inputs = item.querySelectorAll('.command-field-input, .command-field-select');
                commands.push({
                    deviceName: inputs[0].value,
                    sensorName: inputs[1].value,
                    sensorType: inputs[2].value,
                    command: inputs[3].value
                });
            });
            
            // 保存到localStorage（实际项目中应该发送到服务器）
            const sceneData = {
                name: sceneName,
                description: sceneDesc,
                project: document.getElementById('projectInput').value,
                lastExec: document.getElementById('lastExecInput').value,
                commands: commands,
                timestamp: Date.now()
            };
            
            localStorage.setItem('currentScene', JSON.stringify(sceneData));
            
            alert('场景保存成功！');
            location.href = 'scene-manage.html';
        }
        
        // 取消编辑
        function cancelEdit() {
            if (confirm('确定要取消编辑吗？未保存的更改将丢失。')) {
                location.href = 'scene-manage.html';
            }
        }
    </script>
</body>
</html>
